package com.android.lovely.room.role

import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.collectLatest
import java.util.concurrent.ConcurrentHashMap

/**
 *
 * @author why
 * @date 2025/4/6 18:30
 */
object CacheRoleServer {

    private val roleCache = ConcurrentHashMap<Int, CreateRole>()

    fun CoroutineScope.observeRole(id: Int, block: suspend (CreateRole) -> Unit){
        val cacheEntry = roleCache[id]
        launchSafety {
            CreateRoleDataBase.dao.getRoleFlow(id).collectLatest {
                block.invoke(it ?: return@collectLatest)
            }
        }
        if (cacheEntry != null) {
            launchSafety {
                block.invoke(cacheEntry)
            }
            return
        }
        val createRole = CreateRole(id)
        roleCache[id] = createRole
        launchSafety {
            block.invoke(createRole)
        }
    }

    fun remove(id: Int) {
        roleCache.remove(id)
    }

    fun update(role: CreateRole) {
        roleCache[role.id] = role
    }
}